# -*- coding: utf-8 -*-

import spider_logging
import sqlite3

from model import AmazonProduct

logger = spider_logging.get_logger(__name__)


class _DB:
    file = 'spider.sqlite'


def init_db(db='spider.sqlite'):
    _DB.file = db

    sqlite3.connect(_DB.file).execute('''create table if not exists amazon_product (
        id integer primary key autoincrement,
        title text,
        money_symbol varchar(16),
        price numeric,
        main_img text,
        rating integer,
        question text,
        answer text
        )''')


def persist(product: AmazonProduct):
    with sqlite3.connect(_DB.file) as conn:
        conn.execute('''insert into amazon_product (title, money_symbol, price, main_img, rating, question, answer)
    values (?, ?, ?, ?, ?, ?, ?)
    ''', product)

        logger.log(spider_logging.EXTRACTION, f"产品数据已入库: product={product}")
